import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import getUserId from '@/utils/getUserId';

export async function GET(req: NextRequest, { params }: { params: { momentId: string } }) {
  try {
    const userId = getUserId(req);
    const { momentId } = params;

    const moment = await prisma.moment.findUnique({
      where: { id: momentId },
      include: {
        author: {
          select: {
            id: true,
            nickname: true,
            avatar: true,
          },
        },
        likes: {
          orderBy: {
            createdAt: 'desc',
          },
          include: {
            user: {
              select: {
                id: true,
                nickname: true,
                avatar: true,
              },
            },
          },
        },
      },
    });

    if (!moment) {
      return NextResponse.json({ error: '动态不存在' }, { status: 404 });
    }

    let isLikedByMe = false;
    if (userId) {
        isLikedByMe = moment.likes.some((like) => like.userId === userId);
    }

    const response = {
        ...moment,
        isLikedByMe,
        likesCount: moment.likes.length,
    };

    return NextResponse.json(response);
  } catch (error) {
    console.error('获取动态详情失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
} 